using BasicData.API.Application.Command;
using BasicData.API.Dtos;
using BasicData.Domain.Entities;
using BasicData.ErrorCode;
using BasicData.Infrastructure.Interfasce;
using MediatR;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace BasicData.API.Application.CommandHandlers
{
    /// <summary>
    /// 获取生产信息命令处理器
    /// </summary>
    public class GetProductionInfoCommandHandler : IRequestHandler<GetProductionInfoCommand, APIResult<List<ProductionInfoDTO>>>
    {
        private readonly IBaseRepositroy<ProductionInfo> _productionInfoRepository;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="productionInfoRepository">生产信息仓储</param>
        public GetProductionInfoCommandHandler(IBaseRepositroy<ProductionInfo> productionInfoRepository)
        {
            _productionInfoRepository = productionInfoRepository;
        }

        /// <summary>
        /// 处理获取生产信息命令
        /// </summary>
        /// <param name="request">命令请求</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>生产信息列表</returns>
        public async Task<APIResult<List<ProductionInfoDTO>>> Handle(GetProductionInfoCommand request, CancellationToken cancellationToken)
        {
            try
            {
                // 获取所有未删除的生产信息
                var query = _productionInfoRepository.GetAllAsync().Where(p => !p.IsDeleted);

                // 获取数据并转换为DTO
                var productionInfos = await query
                    .Select(p => new ProductionInfoDTO
                    {
                        Id = p.Id,
                        BatchNumber = p.BatchNumber,
                        ShelfLifeDays = p.ShelfLifeDays,
                        ProductionLicenseNumber = p.ProductionLicenseNumber,
                        ManufacturerName = p.ManufacturerName,
                        CoverImageUrl = p.CoverImageUrl,
                        GoodsId = p.GoodsId,
                        CreatedTime = p.CreatedTime,
                        ModifiedTime = p.ModifiedTime,
                        CreatedBy = p.CreatedBy,
                        ModifiedBy = p.ModifiedBy,
                        OperatedBy = p.OperatedBy,
                    })
                    .ToListAsync(cancellationToken);

                // 返回成功结果
                return new APIResult<List<ProductionInfoDTO>>
                {
                    Code = ResultCode.查询成功,
                    Message = "获取生产信息成功",
                    Data = productionInfos
                };
            }
            catch (Exception ex)
            {
                return new APIResult<List<ProductionInfoDTO>>
                {
                    Code = ResultCode.查询失败,
                    Message = $"获取生产信息失败: {ex.Message}"
                };
            }
        }
    }
} 